#include "mainmenuwindow.h"
#include "ui_MainMenuWindow.h"
#include "sqlConnection.h"
#include <iostream.h>
#include "mainwindow.h"
#include <stdlib.h>

TabWidget::TabWidget(QWidget *parent):
        QTabWidget(parent),
        ui(new Ui::TabWidget)
{
    ui->setupUi(this);
    //this->db = sqlConnection::startConnection();
    //this->db.open();
    myQuery = new QSqlQuery(this->db);
    this->removeTab(2);
    this->removeTab(2);

    this->setCurrentIndex(0);

    this->table = new QSqlQueryModel(this);
    this->table->setQuery("SELECT * FROM users WHERE deleted = false");
    ui->tableView->setModel(this->table);
    ui->tableView->show();
    ui->searchUserUpdate->setEnabled(false);

    this->groupTable = new QSqlQueryModel(this);
    this->groupTable->setQuery("SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
                               +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                               +QString(" cr.nombre as carrera ")
                               +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                               +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                               +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                               +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                               +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = false"));
    ui->tablaMaterias->setModel(this->groupTable);
    ui->tablaMaterias->show();

    this->newCarrerBoxValue = 0;
    this->newPlanBoxValue = 0;
    this->newUserTypeBoxValue = 1;
    this->selectedUser = 0;
    this->teacherComboData = new QSqlQueryModel(this);
    this->teacherComboData->setQuery("SELECT nombre,id FROM users WHERE type=2");
    ui->searchTeacher->setModel(this->teacherComboData);
    ui->searchTeacher->show();
    ui->newTeacher->setModel(this->teacherComboData);
    ui->newTeacher->show();

    this->scheduleComboData = new QSqlQueryModel(this);
    this->scheduleComboData->setQuery("SELECT description,id FROM horas");
    ui->searchSchedule->setModel(this->scheduleComboData);
    ui->newSchedule->setModel(this->scheduleComboData);
    ui->searchSchedule->show();
    ui->newSchedule->show();

    this->classComboData = new QSqlQueryModel(this);
    this->classComboData->setQuery("SELECT nombre,id FROM materias");
    ui->searchClassId->setModel(this->classComboData);
    ui->newClassId->setModel(this->classComboData);
    ui->searchClassId->show();
    ui->newClassId->show();
}

void TabWidget::clearNewUserFields(){
    ui->newId->setText("");
    ui->newName->setText("");
    ui->newDirection->setText("");
    ui->newRepeatPass->setText("");

    ui->newCarrera->setCurrentIndex(0);
    ui->comboBox->setCurrentIndex(0);
    ui->newUserType->setCurrentIndex(0);

    this->newCarrerBoxValue = 0;
    ui->newDate->setDate(QDate(2000,1,1));
    this->newPlanBoxValue = 0;
    ui->newPassword->setText("");
    this->newUserTypeBoxValue = 1;
}

TabWidget::~TabWidget()
{
    delete ui;
}

void TabWidget::changeEvent(QEvent *e)
{
    QTabWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void TabWidget::on_pushButton_clicked()
{
    this->removeTab(0);
    this->addTab(ui->tabUsuarios,"Usuarios");
    this->addTab(ui->tabMaterias,"Grupos");
    this->setCurrentIndex(0);
    this->resize(800,600);
    ((MainWindow*)this->parent())->resize(800,600);
}

void TabWidget::on_add_clicked()
{
    this->clearNewUserFields();
    this->addTab(ui->tabAlta,"Nuevo Usuario");
    //ui->tabAlta->show();
    this->setCurrentIndex(2);
    this->removeTab(0);
    this->removeTab(0);
    this->resize(640,300);
    ((MainWindow*)this->parent())->resize(640,300);
    myQuery->exec("SELECT max(id) from users");
    myQuery->next();
    bool ok;
    ui->newId->setText(QString::number(myQuery->value(0).toInt(&ok)+1));
}

void TabWidget::on_newCarrera_currentIndexChanged(int index)
{
    this->newCarrerBoxValue = ui->newCarrera->currentIndex();
}

void TabWidget::on_comboBox_currentIndexChanged(int index)
{
    this->newPlanBoxValue = ui->comboBox->currentIndex();
}

void TabWidget::on_newUserType_currentIndexChanged(int index)
{
    this->newUserTypeBoxValue = ui->newUserType->currentIndex()+1;
}

void TabWidget::on_newButton_clicked()
{
    this->myQuery->exec("INSERT INTO users VALUES ("
                        +ui->newId->text()+",'"+ui->newName->text()+"','"
                        +ui->newDirection->text()+"',"+QString::number(this->newCarrerBoxValue)+",'"
                        +ui->newDate->text()+"',"+"false,"+QString::number(this->newPlanBoxValue)+",'"
                        +ui->newPassword->text()+"',"+QString::number(this->newUserTypeBoxValue)+");");

    /*this->removeTab(0);
    this->addTab(ui->tabUsuarios,"Usuarios");
    this->addTab(ui->tabMaterias,"Materias");
    this->setCurrentIndex(0);
    this->resize(800,600);
    ((MainWindow*)this->parent())->resize(800,600);*/
    myQuery->exec("INSERT INTO kardex(id,alumno_id,materia_id) SELECT nextval('kardex_seq'),u.id, m.id"
                  +QString(" from users u INNER JOIN materias m ON ")
                  +QString(" AND m.carrera_id = u.carrera_id ")
                  +QString(" where u.type = 3 AND u.id = "+ ui->newId->text()));
    std::cout<<myQuery->lastError().databaseText().toStdString()<<std::endl;

    this->table->setQuery("SELECT * FROM users");
    ui->tableView->setModel(this->table);
    ui->tableView->show();

    this->on_pushButton_clicked();

}

void TabWidget::on_searchNewGroup_clicked()
{

    this->teacherComboData->setQuery("SELECT nombre,id FROM users WHERE type=2");
    this->addTab(ui->tabNewGroup,"Nuevo Grupo");
    this->setCurrentIndex(2);
    this->removeTab(0);
    this->removeTab(0);
    this->resize(640,300);
    ((MainWindow*)this->parent())->resize(640,300);
}

void TabWidget::on_newGroupCancel_clicked()
{
    this->on_pushButton_clicked();
    this->setCurrentIndex(1);
}

void TabWidget::on_searchUsers_clicked()
{
    //QSqlTableModel *model = new QSqlTableModel(ui->tableView,db);
    //model->setTable("users");
    //model->select();
    //ui->tableView->setModel(model);
    //model->setFilter("nombre = 'Ricardo' and id = 1");

    QString params;
    params = "";
    if(!ui->searchId->text().isEmpty()){
    params += " and id = " + ui->searchId->text();
    }
    if(!ui->searchName->text().isEmpty()){
    params += " and nombre ILIKE " + QString("'%" + ui->searchName->text() +"%'");
    }
    if(!ui->searchDirection->text().isEmpty()){
    params += " and direccion ILIKE " + QString("'%" + ui->searchDirection->text() +"%'");
    }
    if(ui->searchCarrera->currentIndex() != 0){
        params += " and carrera_id = " + QString::number(ui->searchCarrera->currentIndex());
    }
    if(ui->searchUserType->currentIndex() != 0){
        params += " and type = " + QString::number(ui->searchUserType->currentIndex());
    }
    if(ui->searchPlan->currentIndex() != 0){
        params += " and plan_estudios_id = " + QString::number(ui->searchPlan->currentIndex());
    }
    
    if(ui->checkBox->isChecked()){
    params += " and deleted = true";
    }
    else{
    params += " and deleted = false";
    }

    std::cout<<"SELECT * FROM users WHERE true" << params.toStdString()<<std::endl;


    this->table->setQuery("SELECT * FROM users WHERE true" + params);
    ui->tableView->setModel(this->table);
    ui->tableView->show();
}

void TabWidget::on_tableView_clicked(QModelIndex index)
{
    //std::cout<<QString::number(index.column()).toStdString()<<std::endl;
    //std::cout<<QString::number(index.row()).toStdString()<<std::endl;
    bool ok;
    selectedUser = table->data(table->index(index.row(),0),Qt::DisplayRole).toInt(&ok);
    //std::cout<<((table->data(table->index(index.row(),0),Qt::DisplayRole)).toString()).toStdString()<<std::endl;
    std::cout<<selectedUser<<std::endl;
}

void TabWidget::on_tableView_customContextMenuRequested(QPoint pos)
{

    //NO ENTRAR AQUI!!!!

}

void TabWidget::on_searchUserDelete_clicked()
{
    this->table->setQuery("UPDATE users SET deleted = true WHERE id ="+ QString::number(selectedUser));
    this->table->setQuery("SELECT * FROM users WHERE deleted = false");
    ui->tableView->setModel(this->table);
    ui->tableView->show();
}

void TabWidget::on_searchUserUpdate_clicked()
{
    this->table->setQuery("UPDATE users SET deleted = false WHERE id ="+ QString::number(selectedUser));
    this->table->setQuery("SELECT * FROM users WHERE deleted = true");
    ui->tableView->setModel(this->table);
    ui->tableView->show();
}

void TabWidget::on_checkBox_toggled(bool checked)
{
    ui->searchUserDelete->setEnabled(!checked);
    ui->searchUserUpdate->setEnabled(checked);

    if(!checked)
    {
        this->table->setQuery("SELECT * FROM users WHERE deleted = false");
        ui->tableView->setModel(this->table);
        ui->tableView->show();
    }
    if(checked)
    {
        this->table->setQuery("SELECT * FROM users WHERE deleted = true");
        ui->tableView->setModel(this->table);
        ui->tableView->show();
    }

}

void TabWidget::on_newGroupCarrer_currentIndexChanged(int index)
{
    QString query = "";
    if(index!=0){
        query += " AND carrera_id = "+QString::number(index);

    }
    if(ui->newGroupPlan->currentIndex()!=0){
        query += " AND plan_estudios_id = " + QString::number(ui->newGroupPlan->currentIndex());
   }
    this->classComboData->setQuery("SELECT nombre,id FROM materias WHERE TRUE"+ query );

}

void TabWidget::on_newGroupPlan_currentIndexChanged(int index)
{
    QString query = "";
    if(ui->newGroupCarrer->currentIndex()!=0){
        query += " AND carrera_id = "+QString::number(ui->newGroupCarrer->currentIndex());
    }
    if(ui->newGroupPlan->currentIndex()!=0){
        query += " AND plan_estudios_id = " + QString::number(ui->newGroupPlan->currentIndex());
   }
    this->classComboData->setQuery("SELECT nombre,id FROM materias WHERE TRUE"+ query );
}

void TabWidget::on_newCreateGroup_clicked()
{
    QString query;
    query = "INSERT INTO grupos VALUES(nextval('group_seq'), "
            +QString::number(newGroupScheduleId)+","
            +QString::number(newGroupClassId)+",'"
            +ui->newGroup->text()+"',"+QString::number(newGroupTeacherId)+","
            +QString::number(ui->newGroupPlanAdd->currentIndex())+","
            +QString::number(ui->newGroupCarrerAdd->currentIndex())+");";
    this->myQuery->exec(query);
    std::cout<<query.toStdString()<<std::endl;
    std::cout<<myQuery->lastError().text().toStdString()<<std::endl;

    this->groupTable->setQuery("SELECT g.id as id,hr.description as Horario,mat.nombre as materia "
                               +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                               +QString(" cr.nombre as carrera ")
                               +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                               +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                               +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                               +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                               +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = false"));
    ui->tablaMaterias->setModel(this->groupTable);
    ui->tablaMaterias->show();
    this->on_newGroupCancel_clicked();

}

void TabWidget::on_newSchedule_currentIndexChanged(int index)
{
    this->newGroupScheduleId = this->scheduleComboData->data(scheduleComboData->index(index,1),Qt::DisplayRole).toInt();
}

void TabWidget::on_newClassId_currentIndexChanged(int index)
{
    this->newGroupClassId = this->classComboData->data(classComboData->index(index,1),Qt::DisplayRole).toInt();
}

void TabWidget::on_newTeacher_currentIndexChanged(int index)
{
    this->newGroupTeacherId = this->teacherComboData->data(teacherComboData->index(index,1),Qt::DisplayRole).toInt();
}

void TabWidget::on_newGroupCarrerAdd_currentIndexChanged(int index)
{
    QString query = "";
    if(index!=0){
        query += " AND carrera_id = "+QString::number(index);

    }
    if(ui->newGroupPlanAdd->currentIndex()!=0){
        query += " AND plan_estudios_id = " + QString::number(ui->newGroupPlanAdd->currentIndex());
   }
    this->classComboData->setQuery("SELECT nombre,id FROM materias WHERE TRUE"+ query );
}

void TabWidget::on_newGroupPlanAdd_currentIndexChanged(int index)
{
    QString query = "";
    if(ui->newGroupCarrerAdd->currentIndex()!=0){
        query += " AND carrera_id = "+QString::number(ui->newGroupCarrerAdd->currentIndex());
    }
    if(ui->newGroupPlanAdd->currentIndex()!=0){
        query += " AND plan_estudios_id = " + QString::number(ui->newGroupPlanAdd->currentIndex());
   }
    this->classComboData->setQuery("SELECT nombre,id FROM materias WHERE TRUE"+ query );
}

void TabWidget::on_searchSchedulerCheck_toggled(bool checked)
{
    ui->searchSchedule->setEnabled(checked);
}

void TabWidget::on_searchTeachCheck_toggled(bool checked)
{
    ui->searchTeacher->setEnabled(checked);
}

void TabWidget::on_searchClassCheck_toggled(bool checked)
{
    ui->searchClassId->setEnabled(checked);
}

void TabWidget::on_searchGroups_clicked()
{
    QString params;
    params = "";
    if(ui->searchGroupDelBox->isChecked()){
    params += " and g.deleted = true ";
    }
    if(!ui->searchGroupDelBox->isChecked()){
    params += " and g.deleted = false ";
    }
    if(!ui->searchGroup->text().isEmpty()){
    params += " and clave = '" + ui->searchGroup->text()+"' ";
    }
    if(ui->newGroupCarrer->currentIndex() != 0){
        params += " and g.carrera_id = " + QString::number(ui->newGroupCarrer->currentIndex());
    }
    if(ui->newGroupPlan->currentIndex() != 0){
        params += " and g.plan_id = " + QString::number(ui->newGroupPlan->currentIndex());
    }
    if(ui->searchClassCheck->isChecked()){
        params += " and g.materia_id = " + this->classComboData->data(classComboData->index(ui->searchClassId->currentIndex(),1),Qt::DisplayRole).toString();
    }
    if(ui->searchTeachCheck->isChecked()){
        params += " and g.maestro_id = " + this->teacherComboData->data(teacherComboData->index(ui->searchTeacher->currentIndex(),1),Qt::DisplayRole).toString();
    }
    if(ui->searchSchedulerCheck->isChecked()){
        params += " and g.hora_id = " + this->scheduleComboData->data(scheduleComboData->index(ui->searchSchedule->currentIndex(),1),Qt::DisplayRole).toString();
    }

    QString query;
    query = "SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
            +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
            +QString(" cr.nombre as carrera ")
            +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
            +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
            +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
            +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
            +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE TRUE ") + params;
    std::cout<<query.toStdString()<<std::endl;
    this->groupTable->setQuery(query);

    ui->tablaMaterias->setModel(this->groupTable);
    ui->tablaMaterias->show();

}

void TabWidget::on_searchGroupDelBox_toggled(bool checked)
{
    ui->searchGroupDelBtn->setEnabled(!checked);
    ui->searchGroupUpdateBtn->setEnabled(checked);
    if(!checked){
        this->groupTable->setQuery("SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
                                   +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                                   +QString(" cr.nombre as carrera ")
                                   +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                                   +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                                   +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                                   +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                                   +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = false "));
        ui->tablaMaterias->setModel(this->groupTable);
        ui->tablaMaterias->show();
    }
    if(checked){
        this->groupTable->setQuery("SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
                                   +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                                   +QString(" cr.nombre as carrera ")
                                   +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                                   +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                                   +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                                   +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                                   +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = true "));
        ui->tablaMaterias->setModel(this->groupTable);
        ui->tablaMaterias->show();
    }
}

void TabWidget::on_searchGroupDelBtn_clicked()
{
    this->groupTable->setQuery("UPDATE grupos SET deleted = true WHERE id ="+ QString::number(selectedGroup));
    this->groupTable->setQuery("SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
                               +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                               +QString(" cr.nombre as carrera ")
                               +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                               +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                               +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                               +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                               +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = false "));
    ui->tablaMaterias->setModel(this->groupTable);
    ui->tablaMaterias->show();
}

void TabWidget::on_tablaMaterias_clicked(QModelIndex index)
{
    //std::cout<<QString::number(index.column()).toStdString()<<std::endl;
    //std::cout<<QString::number(index.row()).toStdString()<<std::endl;
    bool ok;
    selectedGroup = groupTable->data(groupTable->index(index.row(),0),Qt::DisplayRole).toInt(&ok);
    //std::cout<<((table->data(table->index(index.row(),0),Qt::DisplayRole)).toString()).toStdString()<<std::endl;
    std::cout<<selectedGroup<<std::endl;
}

void TabWidget::on_searchGroupUpdateBtn_clicked()
{
    this->groupTable->setQuery("UPDATE grupos SET deleted = false WHERE id ="+ QString::number(selectedGroup));
    this->groupTable->setQuery("SELECT g.id as id, hr.description as Horario,mat.nombre as materia "
                               +QString(" ,g.clave as grupo,tch.nombre as maestro, pl.nombre as plan, ")
                               +QString(" cr.nombre as carrera ")
                               +QString(" FROM grupos g INNER JOIN horas hr ON hr.id = g.hora_id ")
                               +QString(" INNER JOIN materias mat ON mat.id = g.materia_id ")
                               +QString(" INNER JOIN users tch ON tch.id = g.maestro_id ")
                               +QString(" INNER JOIN plan pl ON pl.id = g.plan_id ")
                               +QString(" INNER JOIN carrera cr ON cr.id = g.carrera_id WHERE g.deleted = true "));
    ui->tablaMaterias->setModel(this->groupTable);
    ui->tablaMaterias->show();
}
